<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/22
 * Time: 17:06
 */

namespace console\controllers;

use Yii;
use yii\console\Controller;
use linslin\yii2\curl;
use common\models\Goods;

class SeatentController extends Controller
{
    const APP_KEY       = '93029918';
    const SECRET        = 'e90e46638a53404486204970b18a101c';
    const ACCOUNT       = '13162761911';
    const PASSWORD      = 'asd123';
    public $token       = '';
    public $member_id   = '';
    public $i           = 0;

    /**
     * @throws \yii\db\Exception
     * 导入海带目录
     */
    public function actionImportcat()
    {
        $this->login();
        $url = 'http://www.seatent.com/api/mobile/category!topCategory.do?';
        $url .= $this->buildParmas(array('token' => $this->token, 'member_id' => $this->member_id));
        $curl = new curl\Curl();
        $response = $curl->get($url);
        $response = json_decode($response, true);
        if ($response && $response['result'] == 1) {
            $arr_cat = array();
            foreach($response['data'] as $_cat) {
                $arr_exist = Yii::$app->db->createCommand('SELECT * FROM cat_info WHERE cat_id='.$_cat['cat_id'])->queryOne();
                if ($arr_exist) {
                    Yii::$app->db->createCommand("UPDATE cat_info SET cat_order = {$_cat['cat_order']}, goods_count = {$_cat['goods_count']},
                      image = '{$_cat['image']}',list_show = {$_cat['list_show']},name = '{$_cat['name']}',type_id = {$_cat['type_id']},
                      type_name = '{$_cat['type_name']}',udate = ".time()." WHERE cat_id={$_cat['cat_id']}")->execute();
                } else {
                    $arr_cat[]  = array($_cat['cat_id'],$_cat['cat_order'],$_cat['goods_count'],$_cat['image'],$_cat['list_show'],$_cat['name'],$_cat['type_id'],$_cat['type_name'],time());
                }
            }
            if ($arr_cat) {
                Yii::$app->db->createCommand()->batchInsert('cat_info', ['cat_id', 'cat_order', 'goods_count', 'image', 'list_show', 'name', 'type_id', 'type_name', 'udate'], $arr_cat)->execute();
            }
        }
    }

    /**
     * 导入海带商品
     */
    public function actionImportgoods()
    {
        $this->login();
        $url = 'http://www.seatent.com/api/mobile/goods!getFenxiaoSigleGoodsList.do?';
        $urls = $url . $this->buildParmas(array('page' => 1, 'pageSize' => 100, 'member_id' => $this->member_id, 'token' => $this->token));
        $curl = new curl\Curl();
        $response = $curl->get($urls);
        $response = json_decode($response, true);
        if (isset($response['result']) && $response['result'] == 1) {
            $pages = $response['data']['totalPageCount'];
            for($page = 1; $page <= $pages; $page++) {
                echo "total=$pages;current=$page".PHP_EOL;
                $urls = $url . $this->buildParmas(array('page' => $page, 'pageSize' => 100, 'member_id' => $this->member_id, 'token' => $this->token));
                $curl = new curl\Curl();
                $response = $curl->get($urls);
                $response = json_decode($response, true);
                if (isset($response['result']) && $response['result'] == 1) {
                    foreach($response['data']['result'] as $value) {
                        $arr_goods = $this->Importgoodsinfo($value['sn']);  // 海带的sn
                        foreach($arr_goods as $goods) {
                            $model = new Goods();
                            $arr = $model->findByGoodsSn($goods['sn']);  // 系统的sn
                            if ($arr) {
                                $arr->sn    = $arr['sn'];
                                $arr->hd_sn = $goods['hd_sn'];

                                $arr->cat_id = $value['cat_id'];$arr->cat_name = $value['cat_name'];$arr->p_cat_id = $value['p_cat_id'];
                                $arr->p_cat_name = $value['p_cat_name'];$arr->spec_value_id = $value['spec_value_id'];
                                $arr->spec_value = isset($value['spec_value']) ? $value['spec_value'] : '';
                                $arr->trade_type = $value['trade_type'];$arr->trade_type_name = $value['trade_type_name'];
                                $arr->brand_id = $value['brand_id'];
                                $arr->brand_name = isset($value['brand_name']) ? $value['brand_name'] : '';
                                $arr->country_id = $value['country_id'];$arr->country_name = $value['country_name'];
                                $arr->price2 = @$value['price2'] ? $value['price2'] : '';
                                $arr->buy_num = @$value['buy_num']?$value['buy_num']:0;
                                $arr->thumbnail = @$goods['thumbnail']?$goods['thumbnail']:'';$arr->tiny = @$goods['tiny']?$goods['tiny']:'';
                                $arr->original = @$goods['original']?$goods['original']:'';$arr->small = @$goods['small']?$goods['small']:'';
                                $arr->discount = @$value['discount']?$value['discount']:0;

                                $arr->another_name          = @$goods['another_name'] ? $goods['another_name'] : '';
                                $arr->spec_id               = @$goods['spec_id'] ? $goods['spec_id'] : 0;
                                $arr->spec_name             = $goods['spec_name'];
                                $arr->intro                 = $goods['intro'];
                                $arr->expiration_date       = $goods['expiration_date'];
                                $arr->depots                = isset($goods['depots']) ? $goods['depots'] : '';
                                $arr->depotid               = isset($goods['depotid']) ? $goods['depotid'] : '';
                                $arr->weight                = $goods['weight'];
                                $arr->price                 = $goods['price'];
                                $arr->average               = $goods['average'];
                                $arr->life                  = $goods['life'];
                                $arr->enable_store          = $goods['enable_store'];
                                $arr->mktprice              = $goods['mktprice'];
                                $arr->goods_id              = $goods['goods_id'];
                                $arr->goods_name            = $goods['goods_name'];
                                $arr->unit                  = $goods['unit'];
                                $arr->big                   = @$goods['big']?$goods['big']:'';
                                $arr->tax                   = @$goods['tax']?$goods['tax']:0;
                                $arr->intro                 = @$goods['intro']?addslashes($goods['intro']):'';

                                $arr->create_time = time();$arr->status = 1;
                                $arr->update();
                            } else {
                                $model->channel = 1;  // 海带
                                $model->sn = $goods['sn'];
                                $model->hd_sn = $goods['hd_sn'];

                                $model->cat_id = $value['cat_id'];$model->cat_name = $value['cat_name'];$model->p_cat_id = $value['p_cat_id'];
                                $model->p_cat_name = $value['p_cat_name'];$model->spec_value_id = $value['spec_value_id'];
                                $model->spec_value = isset($value['spec_value']) ? $value['spec_value'] : '';
                                $model->trade_type = $value['trade_type'];$model->trade_type_name = $value['trade_type_name'];
                                $model->brand_id = $value['brand_id'];
                                $model->brand_name = isset($value['brand_name']) ? $value['brand_name'] : '';
                                $model->country_id = $value['country_id'];$model->country_name = $value['country_name'];
                                $model->price2 = @$value['price2'] ? $value['price2'] : '';
                                $model->discount = @$value['discount']?$value['discount']:0;
                                $model->buy_num = @$value['buy_num']?$value['buy_num']:0;
                                $model->thumbnail = @$goods['thumbnail']?$goods['thumbnail']:'';$model->tiny = @$goods['tiny']?$goods['tiny']:'';
                                $model->original = @$goods['original']?$goods['original']:'';$model->small = @$goods['small']?$goods['small']:'';

                                $model->another_name          = $goods['another_name'];
                                $model->spec_id               = @$goods['spec_id'] ? $goods['spec_id'] : 0;
                                $model->spec_name             = $goods['spec_name'];
                                $model->intro                 = $goods['intro'];
                                $model->expiration_date       = $goods['expiration_date'];
                                $model->depots                = isset($goods['depots']) ? $goods['depots'] : '';
                                $model->depotid               = isset($goods['depotid']) ? $goods['depotid'] : '';
                                $model->weight                = $goods['weight'];
                                $model->price                 = $goods['price'];
                                $model->average               = $goods['average'];
                                $model->life                  = $goods['life'];
                                $model->enable_store          = $goods['enable_store'];
                                $model->mktprice              = $goods['mktprice'];
                                $model->goods_id              = $goods['goods_id'];
                                $model->goods_name            = $goods['goods_name'];
                                $model->unit                  = $goods['unit'];
                                $model->big                   = @$goods['big']?$goods['big']:'';
                                $model->tax                   = @$goods['tax']?$goods['tax']:0;
                                $model->intro                 = @$goods['intro']?addslashes($goods['intro']):'';

                                $model->create_time = time();$model->status = 1;
                                $model->save();
                            }
                        }
                    }
                }
            }
        }
    }

    public function Importgoodsinfo($goods_sn)
    {
//        $this->login();
        $url = 'http://www.seatent.com/api/mobile/goods!getFenxiaoGoodsById.do?';
        $urls = $url . $this->buildParmas(array('goods_sn' => $goods_sn, 'member_id' => $this->member_id, 'token' => $this->token));
        $curl = new curl\Curl();
        $response = $curl->get($urls);
        $response = json_decode($response, true);
        $arr_goods = array();
        if (isset($response['result']) && $response['result'] == 1) {
            foreach($response['data']['specs'] as $s_key => $s_value) {
                $arr_goods[$s_value['num']]['sn']              = $s_value['psn'].'_'.$s_value['productid'];
                $arr_goods[$s_value['num']]['hd_sn']           = $s_value['psn'];
                $arr_goods[$s_value['num']]['weight']          = $s_value['weight'];
                $arr_goods[$s_value['num']]['depotid']         = $s_value['depotid'];
                $arr_goods[$s_value['num']]['depots']          = $s_value['depots'];
                $arr_goods[$s_value['num']]['another_name']    = @$s_value['another_name']?$s_value['another_name']:'';
                $arr_goods[$s_value['num']]['price']           = $s_value['price'];
                $arr_goods[$s_value['num']]['average']         = $s_value['average'];
                $arr_goods[$s_value['num']]['spec_value']      = $s_value['spec_value'];
                $arr_goods[$s_value['num']]['spec_value_id']   = $s_value['spec_value_id'];
                $arr_goods[$s_value['num']]['spec_name']       = $s_value['spec_name'];
                $arr_goods[$s_value['num']]['life']            = $s_value['life'];
                $arr_goods[$s_value['num']]['enable_store']    = $s_value['enable_store'];
                $arr_goods[$s_value['num']]['mktprice']        = $s_value['mktprice'];
                $arr_goods[$s_value['num']]['goods_id']        = $response['data']['goods_id'];
                $arr_goods[$s_value['num']]['goods_name']      = $response['data']['name'];
                $arr_goods[$s_value['num']]['brand_id']        = $response['data']['brand_id'];
                $arr_goods[$s_value['num']]['brand_name']      = $response['data']['brand_name'];
                $arr_goods[$s_value['num']]['cat_id']          = $response['data']['cat_id'];
                $arr_goods[$s_value['num']]['cat_name']        = $response['data']['cat_name'];
                $arr_goods[$s_value['num']]['unit']            = $response['data']['unit'];
                $arr_goods[$s_value['num']]['thumbnail']       = $response['data']['thumbnail'];
                $arr_goods[$s_value['num']]['tiny']            = $response['data']['tiny'];
                $arr_goods[$s_value['num']]['original']        = $response['data']['original'];
                $arr_goods[$s_value['num']]['small']           = $response['data']['small'];
                $arr_goods[$s_value['num']]['big']             = $response['data']['big'];
                $arr_goods[$s_value['num']]['images']          = $response['data']['images'];
                $arr_goods[$s_value['num']]['intro']           = $response['data']['intro'];
                $arr_goods[$s_value['num']]['expiration_date'] = @$response['data']['expiration_date']?$response['data']['expiration_date']:'';
                $arr_goods[$s_value['num']]['last_modify']     = $response['data']['last_modify'];
                $arr_goods[$s_value['num']]['tax']             = $response['data']['tax'];
            }
        }
        return $arr_goods;
    }

    public function login()
    {
        $url = 'http://www.seatent.com/api/mobile/member!hdLogin.do?';
        $url .= $this->buildParmas(array('username' => self::ACCOUNT, 'password' => md5(self::PASSWORD)));
        $curl = new curl\Curl();
        $response = $curl->get($url);
        $response = json_decode($response, true);
        if ($response && $response['result'] == 1) {
            $this->token        = $response['token'];
            $this->member_id    = $response['member']['member_id'];
        }
    }

    public function buildParmas($params = array())
    {
        $params['appkey']  = self::APP_KEY;
        $params['timestamp'] = time() * 1000;
        ksort($params);
        $url = '';
        foreach($params as $key => $value) {
            $url .= "$key=$value&";
        }
        $url = trim($url, '&');
        $tosign = strtoupper(sha1(self::SECRET.$url.self::SECRET, false));
        return $url."&topSign=$tosign";
    }
}